using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

namespace SubversionReports.Utilities
{
    public static class EnumerationHelper
    {
        /// <summary>
        /// Gets the enumeration description.
        /// </summary>
        /// <param name="value">The enumeration value.</param>
        /// <returns></returns>
        public static string GetDescription(Enum value)
        {
            //return GetAttribute<DescriptionAttribute>(value).ToString();
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }

        /// <summary>
        /// Gets the attribute from a specified enumeration of the type specified by the typeparam.
        /// </summary>
        /// <param name="value">The enumeration value.</param>
        /// <returns></returns>
        /// <typeparam name="T">The type of the attribute to return.</typeparam>
        public static T GetAttribute<T>(Enum value)
        {
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
            object[] attributes = fieldInfo.GetCustomAttributes(typeof(T), false);
            return (attributes.Length > 0) ? (T)attributes[0] : default(T);
        }

        /// <summary>
        /// Gets the enum dictionary (for databinding to an enum)
        /// </summary>
        /// <param name="enumType">Type of the enum.</param>
        /// <returns></returns>
        public static Dictionary<int, string> GetEnumDictionary(Type enumType)
        {
            Dictionary<int, string> dictionary = new Dictionary<int, string>();
            foreach (Enum enumValue in Enum.GetValues(enumType))
                dictionary.Add(Int32.Parse(enumValue.ToString("D")), GetDescription(enumValue));
            return dictionary;
        }

        /// <summary>
        /// Gets the enum value from string.
        /// </summary>
        /// <param name="enumStringValue">The enum string value.</param>
        /// <returns></returns>
        public static int GetEnumValueFromString<T>(string enumStringValue)
        {
            foreach (KeyValuePair<int, string> p in GetEnumDictionary(typeof(T)))
                if (enumStringValue.ToUpper().Equals(p.Value.ToUpper()))
                    return p.Key;
            throw new ArgumentOutOfRangeException("enumStringValue", enumStringValue, string.Format("No value found in enum matching string representation."));
        }
    }
}
